import {
  config
} from 'config.js';

import {
  Token
} from 'token.js';

const token = new Token();

/**
 * 默认错误提示
 */
const tips = {
  code: 10001,
  msg: "抱歉,服务君开小差了~"
}

class HTTP {
  request({
    url,
    data = {},
    method = 'GET'
  }) {
    return new Promise((resolve, reject) => {
      this._request(url, resolve, reject, data, method);
    });
  }
  _request(url, resolve, reject, data = {}, method = 'GET') {
    wx.request({
      url: config.baseUrl + url,
      method: method,
      data: data,
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        const code = res.statusCode.toString();
        if (code.startsWith('2')) {
          resolve(res.data);
        } else {
          let err = res.data;
          reject(err);
          this._show_error(err);
        }
      },
      fail: (err) => {
        console.log(err);
        // 访问不到服务器 走到fail
        reject(tips);
        this._show_error(tips);
      }
    });
  }

  /**
   * 私有方法
   */
  _show_error(tip) {
    wx.showToast({
      title: tip.msg,
      icon: 'none',
      duration: 2000
    });
  }
}
export {
  HTTP
}